/*
 * Copyright 2002-2007 the original author or authors.
 *
 * Licensed under the LGPL (Lesser Gnu Public Licence), 
 * Version 2 or above (the "License");
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package test.ro.romanescu.loc4j.web;

import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import ro.romanescu.loc4j.LocalizationException;
import ro.romanescu.loc4j.impl.LocalizationImpl;
import ro.romanescu.loc4j.web.Loc4JTag;

/**
 * Application context listener.
 * This listener intializes the LOC4J library and sets the attributes on the
 * application, in order to make it available throught the application.
 */
public class ApplicationListener implements ServletContextListener {
  private ServletContext context = null;

  /**
   * Notification that the web application initialization process is starting. 
   * All ServletContextListeners are notified of context initialization before any filter or 
   * servlet in the web application is initialized.
   * @param event Event data sent by the container
   */
  public void contextInitialized( ServletContextEvent event ) {
    context = event.getServletContext();
    context.log( "Initializing loc4j localization library" );
    try {
      LocalizationImpl loc4j = new LocalizationImpl();
      loc4j.configure( new URL( "file", null, context.getInitParameter( "LOC4J_CFG" ) ) );

      context.setAttribute( Loc4JTag.LOC4J_LOCALIZATION, loc4j );
      context.setAttribute( Loc4JTag.LOC4J_LANGUAGE, "en_US" );
    }
    catch( LocalizationException ex ) {
      context.log( ex.getMessage(), ex );
    }
    catch( MalformedURLException ex ) {
      context.log( ex.getMessage(), ex );
    }
  }


  /**
   * Notification that the servlet context is about to be shut down. 
   * All servlets and filters have been destroy()ed before any ServletContextListeners are notified of 
   * context destruction.
   * @param event Event data sent by the container
   */
  public void contextDestroyed( ServletContextEvent event ) {
    context = event.getServletContext();
  }
}
